package cn.hzu580.bean;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import cn.hzu580.util.DateUtil;

/**
 * 定期使各种验证码过期
 * @author 沫熊工作室 <a href="http://www.darhao.cc">www.darhao.cc</a>
 */
@Component
public class CodeDaemon {

	private Set<Map<String, Object>> codeSet;
	
	//单位分钟
	private static final int TIME_OUT = 30;
	
	public CodeDaemon(){
		codeSet = new HashSet<Map<String, Object>>();
	}
	
	@Scheduled(cron="0 0/1 * * * ?")
	public void expired(){
		for (Map<String, Object> map : codeSet) {
			Date now = DateUtil.now();
			Date date = (Date) map.get("date");
			if(now.getMinutes() - date.getMinutes() >= TIME_OUT){
				HttpSession httpSession = (HttpSession) map.get("session");
				httpSession.setAttribute((String) map.get("codeType"), null);
			}
		}
	}
	
	/**
	 * 开始为这类验证码倒计时，请在记录验证码到session后调用该方法
	 * @param codeType
	 */
	public void time(String codeType){
		HttpSession httpSession = ServletActionContext.getRequest().getSession();
		Date date = DateUtil.now();
		Map map = new HashMap<String , Object>();
		map.put("session", httpSession);
		map.put("date", date);
		map.put("codeType", codeType);
		codeSet.add(map);
	}
	
	
}
